﻿
using SanmaoTools.Models;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DbType = SqlSugar.DbType;

namespace SanmaoTools.Common.Untils
{
    public class SqlSugarHelper
    {
        private string DbPath = Path.Combine(Environment.CurrentDirectory, "DataBase","Data.db");
        private SqlSugarClient db = null;
        private string _connectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
        public  Type[] tables = { typeof(Element),typeof(BrandAndStoveNumber),typeof(PhysicalProperties),typeof(Archive) };
        public SqlSugarHelper()
        {
            _connectionString = _connectionString.Replace("Data Source=filename", $"Data Source={DbPath}");
            db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = _connectionString, // SQLite 连接字符串
                DbType = DbType.Sqlite, // 指定数据库类型为 SQLite
                IsAutoCloseConnection = false, // 自动关闭连接
                InitKeyType = InitKeyType.Attribute//从实体特性中读取主键自增列信息
            });
            InitDataBase();
        }
        public SqlSugarClient GetInstance()
        {
            return db;
        }
        /// <summary>
        /// 初始化数据库
        /// </summary>
        public void InitDataBase()
        {

            if (!File.Exists(DbPath))
            {
                db.DbMaintenance.CreateDatabase("Data.db",$"{Path.Combine(Environment.CurrentDirectory, "DataBase")}");//创建数据库
                InitTable();
            }
            else
            {
                var list= db.DbMaintenance.GetTableInfoList().Select(t => t.Name).ToList();
                foreach( var t in tables) 
                {
                    if (!list.Contains(t.Name)) db.CodeFirst.InitTables(t);
                }
                
            }

        }

        public void InitTable()
        {
            db.CodeFirst.InitTables(tables);
        }

    }
}
